package com.jaya.budan.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.heytap.msp.push.HeytapPushManager;
import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.hms.aaid.HmsInstanceId;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.fragment.ChatFragment;
import com.jaya.budan.fragment.NearByFragment;
import com.jaya.budan.fragment.SquareFragment;
import com.jaya.budan.fragment.TopicFragment;
import com.jaya.budan.thirdpush.GenerateTestUserSig;
import com.jaya.budan.thirdpush.OPPOPushImpl;
import com.jaya.budan.thirdpush.PrivateConstants;
import com.jaya.budan.thirdpush.ThirdPushTokenMgr;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.Utils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.Circle_ImageView;
import com.jaya.budan.views.ExpandableTextView;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMManager;
import com.vivo.push.IPushActionListener;
import com.vivo.push.PushClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.widget.ListPopupWindow.MATCH_PARENT;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private long exitTime = 0;
    private String access_token;
    private DrawerLayout drawerLayout;
    private FrameLayout leftMenu;
    private RadioGroup radio_group;
    private RadioButton radio_main_fujin, radio_main_lt, radio_main_gc, radio_main_topic;
    private FragmentTransaction transition;
    private List<Fragment> fragmentList;
    private NearByFragment nearByFragment;
    private ChatFragment chatFragment;
    private SquareFragment squareFragment;
    private TopicFragment topicFragment;
    private RelativeLayout back, rl_main_grtg, rl_main_dttg, rl_main_my_wallet, rl_main_myxyf, rl_main_vipzx, rl_main_lianxiwomen, rl_main_yjfk, rl_main_quxiao;
    private LinearLayout ll_main_set, ll_main_zhuti, ll_main_yejian, ll_main_recharge, ll_main_care, ll_main_fans, rl_geren_main_update_msg_gxqm, ll_geren_main;
    private Circle_ImageView gr_iv_head;
    private ImageView iv_main_near_by_jilu, iv_geren_main_is_vip;
    private TextView tv_main_title, gr_tv_nicename, gr_tv_id, gr_tv_money, gr_tv_square, gr_tv_watch, gr_tv_fans, tv_chat_item_weidu, tv_main_yejian;
    private ExpandableTextView gr_tv_remark;
    private User_Limit user_limit;
    private TabLayout tab_layout;
    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        //隐藏状态栏时，获取状态栏高度
        int statusBarHeight = ToolUtils.getStatusBarHeight(this);

        //初始化状态栏的高度
//        View statusbar = findViewById(R.id.view_statusbar);
//        Toolbar toolbar = findViewById(R.id.toolbar);
        drawerLayout = findViewById(R.id.drawer_layout);
        leftMenu = findViewById(R.id.menu_frame);
        radio_group = findViewById(R.id.radio_group);
        radio_main_fujin = findViewById(R.id.radio_main_fujin);
        radio_main_lt = findViewById(R.id.radio_main_lt);
        radio_main_gc = findViewById(R.id.radio_main_gc);
        radio_main_topic = findViewById(R.id.radio_main_topic);
        back  = findViewById(R.id.back);
        rl_main_grtg  = findViewById(R.id.rl_main_grtg);
        rl_main_dttg  = findViewById(R.id.rl_main_dttg);
        rl_main_my_wallet  = findViewById(R.id.rl_main_my_wallet);
        rl_main_myxyf  = findViewById(R.id.rl_main_myxyf);
        rl_main_vipzx  = findViewById(R.id.rl_main_vipzx);
        rl_main_lianxiwomen  = findViewById(R.id.rl_main_lianxiwomen);
        rl_main_yjfk  = findViewById(R.id.rl_main_yjfk);
        rl_main_quxiao  = findViewById(R.id.rl_main_quxiao);
        ll_main_set  = findViewById(R.id.ll_main_set);
        ll_main_zhuti  = findViewById(R.id.ll_main_zhuti);
        ll_main_yejian  = findViewById(R.id.ll_main_yejian);
        ll_main_recharge  = findViewById(R.id.ll_main_recharge);
        ll_geren_main = findViewById(R.id.ll_geren_main);
        rl_geren_main_update_msg_gxqm  = findViewById(R.id.rl_geren_main_update_msg_gxqm);
        gr_iv_head = findViewById(R.id.gr_iv_head);
        iv_main_near_by_jilu = findViewById(R.id.iv_main_near_by_jilu);
        tv_main_title = findViewById(R.id.tv_main_title);
        tv_chat_item_weidu = findViewById(R.id.tv_chat_item_weidu);
        tv_main_yejian = findViewById(R.id.tv_main_yejian);
        gr_tv_nicename = findViewById(R.id.gr_tv_nicename);
        gr_tv_id = findViewById(R.id.gr_tv_id);
        gr_tv_money = findViewById(R.id.gr_tv_money);
        gr_tv_remark = findViewById(R.id.gr_tv_remark);
        gr_tv_square = findViewById(R.id.gr_tv_square);
        gr_tv_watch = findViewById(R.id.gr_tv_watch);
        gr_tv_fans = findViewById(R.id.gr_tv_fans);
        iv_geren_main_is_vip = findViewById(R.id.iv_geren_main_is_vip);
        ll_main_care = findViewById(R.id.ll_main_care);
        ll_main_fans = findViewById(R.id.ll_main_fans);
        tab_layout = findViewById(R.id.tab_layout);
        SharedPreferences preferences = getSharedPreferences("main_yejian", Context.MODE_PRIVATE);
        if (preferences.getString("yejian", "").equals("夜间")){
            tv_main_yejian.setText("夜间");
        } else {
            tv_main_yejian.setText("白天");
        }
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(MATCH_PARENT, statusBarHeight);
//        statusbar.setLayoutParams(params);
        //获取侧边栏默认宽度
        ViewGroup.LayoutParams leftParams = leftMenu.getLayoutParams();
        //获取屏幕宽度
        final int width = ToolUtils.getWindowWidth(this);
        //获取屏幕高度
        final int height = ToolUtils.getFullActivityHeight(this);
        //设置侧边的宽高(如果不重新设置，即时设置match_parent也只能占屏幕百分80)
        leftParams.width = width;
        leftParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
        leftMenu.setLayoutParams(leftParams);

        //将ToolBar与ActionBar关联
//        setSupportActionBar(toolbar);
//        //另外openDrawerContentDescRes 打开图片   closeDrawerContentDescRes 关闭图片
//        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, 0, 0);
//        //初始化状态
//        drawerLayout.addDrawerListener(toggle);
//        toggle.syncState();
        //设置背景蒙层颜色
        drawerLayout.setScrimColor(Color.parseColor("#B8BDC6"));
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerStateChanged(int newState) {
                //侧边栏状态
            }

            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
                //获取主页内容view
                View mContent = drawerLayout.getChildAt(0);
                //获取侧边栏内容 view
                View mMenu = drawerView;
                //主页面移动
//                ViewHelper.setTranslationX(mContent, width * slideOffset);
                Log.d("main", "mMenu width:" + mMenu.getMeasuredWidth() + " : " + "window width" + width);
            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                //状态栏打开
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                //状态栏关闭
            }
        });
        postData();
        ll_geren_main.setOnClickListener(this);
        ll_main_care.setOnClickListener(this);
        ll_main_fans.setOnClickListener(this);
        back.setOnClickListener(this);
        rl_main_quxiao.setOnClickListener(this);
        rl_main_grtg.setOnClickListener(this);
        rl_main_dttg.setOnClickListener(this);
        rl_main_my_wallet.setOnClickListener(this);
        rl_main_myxyf.setOnClickListener(this);
        rl_main_vipzx.setOnClickListener(this);
        rl_main_lianxiwomen.setOnClickListener(this);
        rl_main_yjfk.setOnClickListener(this);
        ll_main_set.setOnClickListener(this);
        ll_main_zhuti.setOnClickListener(this);
        ll_main_yejian.setOnClickListener(this);
        ll_main_recharge.setOnClickListener(this);
        rl_geren_main_update_msg_gxqm.setOnClickListener(this);
        iv_main_near_by_jilu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Visit_JiLu_Activity.class);
                intent.putExtra("access_token", access_token);
                startActivity(intent);
            }
        });
        fragmentList = new ArrayList<>();
        nearByFragment = NearByFragment.newInstance();
        fragmentList.add(nearByFragment);
        hideOthersFragment(nearByFragment, true);
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @SuppressLint("NonConstantResourceId")
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radio_main_fujin:
                        radio_main_fujin.setTextColor(Color.parseColor("#000000"));
                        radio_main_fujin.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_fujin,0,0);
                        radio_main_lt.setTextColor(Color.parseColor("#999999"));
                        radio_main_lt.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_lt_no,0,0);
                        radio_main_gc.setTextColor(Color.parseColor("#999999"));
                        radio_main_gc.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_gc,0,0);
                        radio_main_topic.setTextColor(Color.parseColor("#999999"));
                        radio_main_topic.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_ht_no,0,0);
                        hideOthersFragment(nearByFragment, false);
                        tv_main_title.setVisibility(View.VISIBLE);
                        tab_layout.setVisibility(View.GONE);
                        tv_main_title.setText("交友");
                        tv_chat_item_weidu.setVisibility(View.GONE);
                        iv_main_near_by_jilu.setImageResource(R.mipmap.iv_xiugai);
                        iv_main_near_by_jilu.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(MainActivity.this, Visit_JiLu_Activity.class);
                                intent.putExtra("access_token", access_token);
                                startActivity(intent);
                            }
                        });
                        break;
                    case R.id.radio_main_lt:
                        radio_main_fujin.setTextColor(Color.parseColor("#999999"));
                        radio_main_fujin.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_fujin_no,0,0);
                        radio_main_lt.setTextColor(Color.parseColor("#000000"));
                        radio_main_lt.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_lt,0,0);
                        radio_main_gc.setTextColor(Color.parseColor("#999999"));
                        radio_main_gc.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_gc,0,0);
                        radio_main_topic.setTextColor(Color.parseColor("#999999"));
                        radio_main_topic.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_ht_no,0,0);
                        if (chatFragment == null){
                            chatFragment = ChatFragment.newInstance();
                            fragmentList.add(chatFragment);
                            hideOthersFragment(chatFragment, true);
                        } else {
                            hideOthersFragment(chatFragment, false);
                        }
                        tv_main_title.setVisibility(View.VISIBLE);
                        tab_layout.setVisibility(View.GONE);
                        tv_main_title.setText("聊天");
                        tv_chat_item_weidu.setVisibility(View.GONE);
                        iv_main_near_by_jilu.setImageResource(R.mipmap.iv_main_chat);
                        iv_main_near_by_jilu.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(MainActivity.this, Message_Set_Activity.class);
                                intent.putExtra("access_token", access_token);
                                startActivity(intent);
                            }
                        });
                        break;
                    case R.id.radio_main_gc:
                        if (squareFragment == null){
                            squareFragment = SquareFragment.newInstance();
                            fragmentList.add(squareFragment);
                            hideOthersFragment(squareFragment, true);
                        } else {
                            hideOthersFragment(squareFragment, false);
                        }
                        radio_main_fujin.setTextColor(Color.parseColor("#999999"));
                        radio_main_fujin.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_fujin_no,0,0);
                        radio_main_lt.setTextColor(Color.parseColor("#999999"));
                        radio_main_lt.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_lt_no,0,0);
                        radio_main_gc.setTextColor(Color.parseColor("#000000"));
                        radio_main_gc.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_gc_yes,0,0);
                        radio_main_topic.setTextColor(Color.parseColor("#999999"));
                        radio_main_topic.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_ht_no,0,0);
                        tv_main_title.setVisibility(View.GONE);
                        tab_layout.setVisibility(View.VISIBLE);
                        postCountData();
                        iv_main_near_by_jilu.setImageResource(R.mipmap.iv_square_msg);
                        iv_main_near_by_jilu.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(MainActivity.this, Message_Square_Activity.class);
                                intent.putExtra("access_token", access_token);
                                startActivity(intent);
                            }
                        });
                        break;
                    case R.id.radio_main_topic:
                        if (topicFragment == null){
                            topicFragment = TopicFragment.newInstance();
                            fragmentList.add(topicFragment);
                            hideOthersFragment(topicFragment, true);
                        } else {
                            hideOthersFragment(topicFragment, false);
                        }
                        radio_main_fujin.setTextColor(Color.parseColor("#999999"));
                        radio_main_fujin.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_fujin_no,0,0);
                        radio_main_lt.setTextColor(Color.parseColor("#999999"));
                        radio_main_lt.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_lt_no,0,0);
                        radio_main_gc.setTextColor(Color.parseColor("#999999"));
                        radio_main_gc.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_gc,0,0);
                        radio_main_topic.setTextColor(Color.parseColor("#000000"));
                        radio_main_topic.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.mipmap.radio_ht_yes,0,0);
                        tv_main_title.setVisibility(View.VISIBLE);
                        tab_layout.setVisibility(View.GONE);
                        tv_main_title.setText("话题圈子");
                        tv_chat_item_weidu.setVisibility(View.GONE);
                        iv_main_near_by_jilu.setImageResource(R.mipmap.iv_main_chat);
                        iv_main_near_by_jilu.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ToolUtils.showToast(MainActivity.this, "该功能暂未上线，敬请期待。。。");
                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        });
        prepareThirdPushToken();//离线推送设置
    }

    public void prepareThirdPushToken() {
        ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
        if (Utils.isBrandHuawei()) {
            // 华为离线推送
            new Thread() {
                @Override
                public void run() {
                    try {
                        // read from agconnect-services.json
                        String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/app_id");
                        String token = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, "HCM");
                        Log.d("chat", "huawei get token:" + token);
                        if(!TextUtils.isEmpty(token)) {
                            ThirdPushTokenMgr.getInstance().setThirdPushToken(token);
                            ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
                        }
                    } catch (com.huawei.hms.common.ApiException e) {
                        Log.d("chat", "huawei get token failed, " + e);
                    }
                }
            }.start();
        } else if (Utils.isBrandVivo()) {
            // vivo离线推送
            Log.d("chat", "vivo support push: " + PushClient.getInstance(getApplicationContext()).isSupport());
            PushClient.getInstance(getApplicationContext()).turnOnPush(new IPushActionListener() {
                @Override
                public void onStateChanged(int state) {
                    if (state == 0) {
                        String regId = PushClient.getInstance(getApplicationContext()).getRegId();
                        Log.d("chat", "vivopush open vivo push success regId = " + regId);
                        ThirdPushTokenMgr.getInstance().setThirdPushToken(regId);
                        ThirdPushTokenMgr.getInstance().setPushTokenToTIM();
                    } else {
                        // 根据vivo推送文档说明，state = 101 表示该vivo机型或者版本不支持vivo推送，链接：https://dev.vivo.com.cn/documentCenter/doc/156
                        Log.d("chat", "vivopush open vivo push fail state = " + state);
                    }
                }
            });
        } else if (HeytapPushManager.isSupportPush()) {
            // oppo离线推送
            OPPOPushImpl oppo = new OPPOPushImpl();
            oppo.createNotificationChannel(this);
            HeytapPushManager.register(this, PrivateConstants.OPPO_PUSH_APPKEY, PrivateConstants.OPPO_PUSH_APPSECRET, oppo);
        } else if (Utils.isGoogleServiceSupport()) {
            // 谷歌推送
        }
    }

    @SuppressLint({"WrongConstant", "NonConstantResourceId"})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                drawerLayout.openDrawer(Gravity.START);//开启侧滑栏---左边
//                drawerLayout.openDrawer(Gravity.END);//开启侧滑栏---右边
                break;
            case R.id.rl_main_quxiao:
                drawerLayout.closeDrawers();//关闭侧滑栏
                break;
            case R.id.ll_geren_main:
                Intent intent = new Intent(this, GeRen_Main_Activity.class);
                intent.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent.putExtra("uid", user_limit.getUid());
                }
                startActivity(intent);
                break;
            case R.id.rl_main_grtg:
                Intent intent0 = new Intent(this, GeRenTG_Activity.class);
                intent0.putExtra("access_token", access_token);
                startActivity(intent0);
                break;
            case R.id.rl_main_dttg:
                Intent intent1 = new Intent(this, DongTaiTG_DJ_Activity.class);
                intent1.putExtra("access_token", access_token);
                startActivity(intent1);
                break;
            case R.id.rl_main_my_wallet:
                Intent intent2 = new Intent(this, My_Wallet_Activity.class);
                intent2.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent2.putExtra("money", user_limit.getMoney() + "");
                    intent2.putExtra("is_certify", user_limit.getIs_certify());
                    intent2.putExtra("is_bank", user_limit.getIs_bank());
                }
                startActivity(intent2);
                break;
            case R.id.rl_main_myxyf:
                Intent intent4 = new Intent(this, XinYunF_Activity.class);
                intent4.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent4.putExtra("user_limit", user_limit);
                }
                startActivity(intent4);
                break;
            case R.id.rl_main_vipzx:
                Intent intent5 = new Intent(this, VIP_ZX_Activity.class);
                intent5.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent5.putExtra("user_limit", user_limit);
                }
                startActivity(intent5);
                break;
            case R.id.rl_main_lianxiwomen:
                Intent intent6 = new Intent(this, LianXiUS_Activity.class);
                intent6.putExtra("access_token", access_token);
                startActivity(intent6);
                break;
            case R.id.rl_main_yjfk:
                Intent intent7 = new Intent(this, FeedBack_Activity.class);
                intent7.putExtra("access_token", access_token);
                startActivity(intent7);
                break;
            case R.id.ll_main_set:
                Intent intent8 = new Intent(this, Set_Activity.class);
                intent8.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent8.putExtra("username", user_limit.getUsername());
                }
                startActivity(intent8);
                break;
            case R.id.ll_main_zhuti:
                ToolUtils.showToast(this, "新功能开发中，敬请期待！");
                break;
            case R.id.ll_main_recharge:
                Intent intent9 = new Intent(this, My_Wallet_Recharge_Activity.class);
                intent9.putExtra("access_token", access_token);
                startActivity(intent9);
                break;
            case R.id.ll_main_care:
                Intent intent10 = new Intent(this, GeRen_Main_Fans_Activity.class);
                intent10.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent10.putExtra("uid", user_limit.getUid());
                    intent10.putExtra("fans", user_limit.getFans());
                    intent10.putExtra("watch", user_limit.getWatch());
                }
                intent10.putExtra("type", 2);
                intent10.putExtra("care", 1);
                startActivity(intent10);
                break;
            case R.id.ll_main_fans:
                Intent intent11 = new Intent(this, GeRen_Main_Fans_Activity.class);
                intent11.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent11.putExtra("uid", user_limit.getUid());
                    intent11.putExtra("fans", user_limit.getFans());
                    intent11.putExtra("watch", user_limit.getWatch());
                }
                intent11.putExtra("type", 1);
                intent11.putExtra("care", 1);
                startActivity(intent11);
                break;
            case R.id.rl_geren_main_update_msg_gxqm:
                Intent intent12 = new Intent(this, GeRen_Update_Msg_GXQM_Activity.class);
                intent12.putExtra("access_token", access_token);
                if (user_limit != null){
                    intent12.putExtra("user_limit", user_limit);
                }
                startActivity(intent12);
                break;
            case R.id.ll_main_yejian:
                SharedPreferences preferences = getSharedPreferences("main_yejian", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                if (tv_main_yejian.getText().equals("夜间")){
                    Log.d("main", "夜间");
                    editor.putString("yejian", "白天");
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);//夜间
//                    recreate();//重启
                } else {
                    Log.d("main", "白天");
                    editor.putString("yejian", "夜间");
                    getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);//白天
                    recreate();//重启
                }
                editor.apply();
//                int mode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
//                if (mode == Configuration.UI_MODE_NIGHT_YES) {
//                    Log.d("main", "白天");
//                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
//                } else {
//                    Log.d("main", "白---天");//
//                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//                }
//                getWindow().setWindowAnimations(R.style.WindowAnimationFadeInOut);
                break;
            default:
                break;
        }
    }

    /**
     * 动态显示Fragment
     *
     * @param showFragment 要增加的fragment
     * @param add          true：增加fragment；false：切换fragment
     */
    private void hideOthersFragment(Fragment showFragment, boolean add) {
        Bundle bundle = new Bundle();
        transition = getSupportFragmentManager().beginTransaction();
        if (add)
            bundle.putString("access_token", access_token);
        if (user_limit != null){
            bundle.putString("uid", user_limit.getUid() + "");
        }
        showFragment.setArguments(bundle);
        if (! showFragment.isAdded()){
            transition.add(R.id.main_fragment, showFragment);
        }
        for (Fragment fragment : fragmentList) {
            if (showFragment.equals(fragment)) {
                transition.show(fragment);
            } else {
                transition.hide(fragment);
            }
        }
        transition.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 3000) {
                drawerLayout.closeDrawers();//关闭侧滑栏
                exitTime = System.currentTimeMillis() - 2500;
            } else if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToolUtils.showToast(getApplicationContext(), "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                Utils.logOut2(MainActivity.this);
                System.exit(0);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 网络请求
     */
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.gr_information_Url + access_token, null, new Response.Listener<JSONObject>() {
            @SuppressLint("SetTextI18n")
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("main", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        user_limit = gson.fromJson(info.toString(), User_Limit.class);
                        Glide.with(MainActivity.this).load(user_limit.getHead()).apply(new RequestOptions()
                                .placeholder(R.mipmap.iv_main_item).error(R.mipmap.iv_main_item)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
                        ).into(gr_iv_head);
                        gr_tv_nicename.setText("" + user_limit.getNicename());
                        gr_tv_id.setText("ID：" + user_limit.getUid());
                        gr_tv_money.setText("我的布丁：" + user_limit.getMoney());
                        gr_tv_remark.setText("" + user_limit.getRemark());
                        gr_tv_square.setText("" + user_limit.getSquare());
                        gr_tv_watch.setText("" + user_limit.getWatch());
                        gr_tv_fans.setText("" + user_limit.getFans());
                        if (user_limit.getIs_vip() == 1){
                            gr_tv_nicename.setTextColor(Color.parseColor("#FF3B30"));
                            iv_geren_main_is_vip.setVisibility(View.VISIBLE);
                        } else {
                            gr_tv_nicename.setTextColor(Color.parseColor("#000000"));
                            iv_geren_main_is_vip.setVisibility(View.GONE);
                        }
                        // 获取userSig函数
                        String userSig = GenerateTestUserSig.genTestUserSig(user_limit.getUid() + "");
                        TIMManager.getInstance().login(user_limit.getUid() + "", userSig, new TIMCallBack() {
                            @Override
                            public void onError(int code, String desc) {
                                ToolUtils.showToast(MainActivity.this, "失败, errCode = " + code + ", errInfo = " + desc);
                            }

                            @Override
                            public void onSuccess() {

                            }
                        });
//                        V2TIMUserFullInfo v2TIMUserFullInfo = new V2TIMUserFullInfo();
//                        v2TIMUserFullInfo.setFaceUrl(user_limit.getHead());
//                        v2TIMUserFullInfo.setNickname("" + user_limit.getNicename());
//                        v2TIMUserFullInfo.setSelfSignature(user_limit.getRemark() + "");
//                        V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo, new V2TIMCallback() {
//                            @Override
//                            public void onError(int code, String desc) {
//                                ToolUtils.showToast(MainActivity.this, "Error code = " + code + ", desc = " + desc);
//                            }
//
//                            @Override
//                            public void onSuccess() {
//                                TUIKitConfigs.getConfigs().getGeneralConfig().setUserFaceUrl(user_limit.getHead());
//                                TUIKitConfigs.getConfigs().getGeneralConfig().setUserNickname(user_limit.getNicename());
//                                TUIKitConfigs.getConfigs().getGeneralConfig().setUserSig(user_limit.getRemark());
//                            }
//                        });
                    } else {
                        ToolUtils.showToast(MainActivity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(MainActivity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postCountData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.square_msg_count_Url + access_token, null, new Response.Listener<JSONObject>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        int count = info.optInt("aCount");
                        if (count > 0){
                            tv_chat_item_weidu.setVisibility(View.VISIBLE);
                            tv_chat_item_weidu.setText("" + count);
                        } else {
                            tv_chat_item_weidu.setVisibility(View.GONE);
                        }

                    } else {
                        ToolUtils.showToast(MainActivity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(MainActivity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        postData();
        if (nearByFragment != null){
            transition.remove(nearByFragment);
        }
        if (chatFragment != null){
            transition.remove(chatFragment);
        }
    }
}
